package lib.Com;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.net.Socket;

public class ServerWorker implements Runnable{
	/**
	 * Class to handle a server request.
	 */
	protected Socket clientSocket;
    protected String serverText;
    
    public ServerWorker(Socket clientSocket, String serverText) {
        this.clientSocket = clientSocket;
        this.serverText   = serverText;
    }
    
    public void run() {
        try {
        	//Receive object data
        	InputStream is = clientSocket.getInputStream();  
			ObjectInputStream ois = new ObjectInputStream(is);
			
			Object obj = null;
			
			try{
				obj = ois.readObject();
			}catch(IOException ex){
				ex.printStackTrace();
			}catch(ClassNotFoundException ex){
				ex.printStackTrace();
			}

			KnownClient client = null;
			for(String id : Container.knownClients.keySet()) {
				if(Container.knownClients.get(id).getIPlocal().equals(clientSocket.getInetAddress().toString().split("/")[1]) || Container.knownClients.get(id).getIPpublic().equals(clientSocket.getInetAddress().toString().split("/")[1])) {
					client = Container.knownClients.get(id);
					break;
				}
			}
			if (client != null) {
				new ObjectHandler(obj, client).start();
			}
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
